package moonhy.c2dm_client;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import moonhy.c2dm_client.ChatColorPicker.OnColorChangedListener;
import moonhy.c2dm_client.dw.ChatData;
import moonhy.c2dm_client.util.JSONSharedPreferences;
import moonhy.c2dm_client.util.httpConnectionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


public class ChatMainActivity extends Activity implements
ChatColorPicker.OnColorChangedListener{
	private String ROOM_NUMBER;
	String TAG;
	
	private LinkedList<ChatData> chatJsonData = new LinkedList<ChatData>();
	
	private ListView chatListView;
	private LinearLayout loadingBarLayout;
	private SharedPreferences prefs;
	private Editor edit;
	private chatAdapter chatListAdapter;
	private OnSharedPreferenceChangeListener listener;
	private ProgressBar dialog;
	private EditText et;
	
	int pageNo		= 0;
	int pageSize	= 30;
	int savedFirstVisibleItem = 0;
	boolean firstPrevItemLoading = true;
	boolean isFinishedLoading = false;
	AlertDialog ax;
	
	ImageView alarmImg;
	ImageView muteImg;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TAG = this.getString(R.string.TAG);
		//ListViewLayout listviewLayout = new ListViewLayout(this, null);
		//setContentView(searchLayout);
		setContentView(R.layout.chat_listview_main);
		
		Bundle extras = getIntent().getExtras();
		ROOM_NUMBER = extras.getString("frm_room_no");
		
		Log.d(TAG, "[ROOM_NUMBER] " + ROOM_NUMBER);
		
		if(ROOM_NUMBER == null)
			finish();
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		edit = prefs.edit();
		chatListView = (ListView)findViewById(R.id.listviewChatList);
		//chatListView = new ListViewLayout(this, null);
		
		if(prefs.getInt("MEM_AUTH", -9) > 0 && ROOM_NUMBER.equals("0")){
			LinearLayout msgBox = (LinearLayout) findViewById(R.id.sendMsgBox);
			msgBox.setVisibility(View.GONE);
			
			Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.chat_bg);
			BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
			bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
			
			LinearLayout layout = (LinearLayout) findViewById(R.id.chatMainLayout);
			layout.setBackgroundDrawable(bitmapDrawable);
		}
		
		//chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		//chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_NORMAL);
		//chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_DISABLED);
		
		dialog = (ProgressBar) findViewById(R.id.chatProgressBar);
		dialog.setVisibility(View.INVISIBLE);
		
		//new initPage(this).execute();
		
		
		JSONArray json_chatRoomList;
		try {
			json_chatRoomList = JSONSharedPreferences.loadJSONArray(this, "gline", "chatRoomList");
			
			for (int i = 0; i < json_chatRoomList.length(); i++) {
				JSONObject jsonObject = json_chatRoomList.getJSONObject(i);
				
				if(jsonObject.getInt("room_no") == Integer.parseInt(ROOM_NUMBER)){
					
					Log.e(TAG, "BG ::::::::::::::: " + jsonObject.getString("bg"));
					
					TextView chatTitle = (TextView) findViewById(R.id.chatTitleText);
					chatTitle.setText(jsonObject.getString("room_name"));
					
					LinearLayout layout = (LinearLayout) findViewById(R.id.chatMainLayout);
					if(jsonObject.getString("bg").substring(0, 1).contains("#")){
						layout.setBackgroundColor(Color.parseColor(jsonObject.getString("bg")));
					}else{
						AssetManager assetManager = getAssets();
                    	InputStream ims = null;
                    	
                    	/*
                    	try {  
                            String[] files = assetManager.list("images/backgrounds");  
                  
                            for(int l=0; l<files.length; l++){
                            		Log.e(TAG, files[l]);
                            }
                        } catch (IOException e1) {  
                            // TODO Auto-generated catch block  
                            e1.printStackTrace();  
                        }  
                        */
                    	
                        try {
                            ims = assetManager.open("images/backgrounds/"+jsonObject.getString("bg"));
                        }
                        catch(IOException ex) {
                        	Log.e(TAG, "BG ::::::::::::::: " + ex.toString());
                        	layout.setBackgroundColor(Color.parseColor("#000000"));
                        }
                        
                        //Drawable d = Drawable.createFromStream(ims, null);  
						//Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.chat_bg);
                        Bitmap bmp = BitmapFactory.decodeStream(ims);
						BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
						bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
						
						layout.setBackgroundDrawable(bitmapDrawable);
					}
					
					
					if(jsonObject.getInt("alarm") == 0){
						alarmImg = (ImageView) findViewById(R.id.alarmImage);
						muteImg  = (ImageView) findViewById(R.id.muteImage);
						alarmImg.setVisibility(View.VISIBLE);
						muteImg.setVisibility(View.GONE);
					}else{
						alarmImg = (ImageView) findViewById(R.id.alarmImage);
						muteImg  = (ImageView) findViewById(R.id.muteImage);
						alarmImg.setVisibility(View.GONE);
						muteImg.setVisibility(View.VISIBLE);
					}
				}
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "glineChat", ROOM_NUMBER);
			Log.e(TAG, "Init Data ==== ");
			
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				ChatData mList = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
						,jsonObject.getString("name"), jsonObject.getString("content")
						,jsonObject.getString("reg_date")
				);
				chatJsonData.add(mList);
				Log.d(TAG, "[CHAT MAIN] Init Data: " + jsonObject.getInt("seqno"));
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		loadingBarLayout = (LinearLayout) View.inflate(this, R.layout.chat_listview_loading, null);
        loadingBarLayout.setVisibility(View.INVISIBLE);
        chatListView.addHeaderView(loadingBarLayout);
		
		chatListAdapter = new chatAdapter(this, R.layout.chat_listview_layout_mine, chatJsonData);
		chatListView.setAdapter(chatListAdapter);
		
		
		
		// 메세지 Send 버튼 클릭 이벤트
		et = (EditText) findViewById(R.id.frm_content);
		Button btn_send	= (Button)findViewById(R.id.sendButton);
		btn_send.setOnClickListener( new OnClickListener(){
			@Override
 			public void onClick(View v) {
 				String content = et.getText().toString();
 				
 				if(!content.trim().equals("")){
 					new sendMessage(getApplicationContext(), content).execute();
 					et.setText("");

 					//chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
 					//InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
 					//inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
 				}
 			}
		});
		
		// 리스트 스크롤 이벤트
		chatListView.setOnScrollListener(new OnScrollListener() {
			
			// @Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}
			
			// @Override
			public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
//				Log.v(TAG, "onScroll");
//				Log.v(TAG, "firstVisibleItem = " + firstVisibleItem);
//				Log.v(TAG, "visibleItemCount = " + visibleItemCount);
//				Log.v(TAG, "totalItemCount = " + totalItemCount);
				
				
				if(totalItemCount > pageSize && firstVisibleItem == 0 && !isFinishedLoading){
					if(savedFirstVisibleItem != firstVisibleItem){
						Log.e(TAG, "firstVisibleItem = " + firstVisibleItem + "  isFinishedLoading" + isFinishedLoading);
						if(loadingBarLayout.getVisibility() == View.INVISIBLE){
							new getPrevChat(getApplicationContext()).execute();
						}
					}
				}else{
				}
				
				savedFirstVisibleItem = firstVisibleItem;
				
			}
		});
		
		
		// 리스트 아이템 클릭 이벤트
		/*
		chatListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Log.d(TAG, "Clicked" + position);
				//view.setBackgroundColor(0x00);
				//chatListView.getChildAt(position).setBackgroundColor(0xFFFF0000);
            }
        });
        */
		
		//String param_seqno = Integer.toString(prefs.getInt("chatSeqno"+ROOM_NUMBER, -1));
		
		// Shared Preference 변경 이벤트
		listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
			@Override
			public void onSharedPreferenceChanged(SharedPreferences arg0, String key) {

				if (key.equalsIgnoreCase("chatMaxSeqno"+ROOM_NUMBER)) {

					Log.i(TAG, "ChatMain [Event Fired] onSharedPreferenceChanged");
					//Toast.makeText(getApplicationContext(), "onSharedPreferenceChanged", Toast.LENGTH_LONG).show();
					//int currentSeqno = arg0.getInt("chatSeqno", 0);
                   
					// DB 다녀오겠습니다~
					JSONArray json_result;
					try {
						json_result = JSONSharedPreferences.loadJSONArray(getApplicationContext(), "glineChat", ROOM_NUMBER);
						//chatJsonData.clear();
						int maxSeqInData = -1;

						for (int i = 0; i < json_result.length(); i++) {
							JSONObject jsonObject = json_result.getJSONObject(i);
							//Log.e(TAG, "SEQ FROM JSON :: " + jsonObject.getInt("seqno") + "    MAX SEQ IN DATA:::" + maxSeqInData);
							
							ChatData mList = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
									,jsonObject.getString("name"), jsonObject.getString("content")
									,jsonObject.getString("reg_date")
							);
							chatJsonData.add(mList);
							Log.d(TAG, "Init Data: " + jsonObject.getInt("seqno"));
						}
						
						int totalChatCount	= prefs.getInt("UnreadCntTotal", 0);
				    	int thisChatCount	= prefs.getInt("UnreadCnt"+ROOM_NUMBER, 0);
						
				        edit.putInt("UnreadCnt"+ROOM_NUMBER, 0);
						edit.putInt("UnreadCntTotal",	totalChatCount - thisChatCount);
						edit.commit();
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					chatListAdapter.notifyDataSetChanged();
					
				}
			}
		};
		prefs.registerOnSharedPreferenceChangeListener(listener);
		
		
		Editor edit = prefs.edit();
		edit.putInt("currentTab", 1);
		
		
		edit.commit();
		new getNewChat(this).execute();
		
	}
	
	public void onStop(){
		super.onStop();
		prefs.unregisterOnSharedPreferenceChangeListener(listener);
	}
	
	private class sendMessage extends AsyncTask<Void, Void, Void>{
		private Context context;
		private String frm_content;
		private int DataSetIdx;
		private boolean status = false;
		JSONObject json;
		JSONObject jsonObject;
		
		private sendMessage(Context context, String frm_content){
			this.context = context;
			this.frm_content = frm_content;
		}

		@Override
		protected void onPreExecute(){
			//chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
			
			ChatData tmp_nd = new ChatData(-1, -1, "나", frm_content,"");
			chatJsonData.addLast(tmp_nd);
			DataSetIdx = 0;
			if(chatJsonData.size() > 0)
				DataSetIdx = chatJsonData.size()-1;
			
			chatListAdapter.notifyDataSetChanged();
			
//			chatListAdapter.getView(DataSetIdx, )
//			newChatProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				
				String param_seqno = Integer.toString(prefs.getInt("chatMaxSeqno"+ROOM_NUMBER, -1));					
				Map<String, String> map = new HashMap<String, String>();
				map.put("frm_content", frm_content);
				map.put("curPageNo", param_seqno);
				map.put("ROOM_NO", ROOM_NUMBER);
				
				String getJSON = hcm.readJSON_GET(getString(R.string.SERVER_URL) + "chat/chat_proc.php", map);
				
				if(!getJSON.equals("")){
					json = new JSONObject(getJSON);
						
					if(!json.isNull("data_result"))
						status = true;
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			Log.d(TAG, "MESSAGE SEND RESULT: " + status);
        	if(status){
        		//chatJsonData.remove(DataSetIdx);
        		
        		chatJsonData.remove(DataSetIdx);
				
				try {
					JSONArray json_result = json.getJSONArray("data_result");
					
					for (int i = 0; i < json_result.length(); i++) {
						JSONObject jsonObject = json_result.getJSONObject(i);
						ChatData mList = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
								,jsonObject.getString("name"), jsonObject.getString("content")
								,jsonObject.getString("reg_date")
						);
						chatJsonData.addLast(mList);
					}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
        	}else{
        		chatJsonData.get(DataSetIdx).setSeqno(-9);
        		chatJsonData.get(DataSetIdx).setReg_Date("failed");
        		//chatListView.setSelection(chatJsonData.size()-1);
				/*View v = chatListView.getChildAt(DataSetIdx);
				
				ProgressBar pb = (ProgressBar) v.findViewById(R.id.newChatProgressBarMine);
				pb.setVisibility(View.GONE);*/
        	}
        	
        	saveNewJSONData(context);
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused)
        {
			/*
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            Editor edit = prefs.edit();
            edit.putInt("chatSeqno", prefs.getInt("chatMaxSeqno",0)).commit();
            */
        	//newChatProgressBar.setVisibility(View.INVISIBLE);
        	if(status){
        		int seq = 0;
    			if(chatJsonData.size() > 0)
    				seq = chatJsonData.get(chatJsonData.size()-1).getSeqno();
    			
        		edit.putInt("chatMaxSeqno"+ROOM_NUMBER, seq).commit();
        	}
        	
			chatListAdapter.notifyDataSetChanged();
        }
	}
	
	public void saveNewJSONData(Context context){
		try{
        	int initSize = 0;
			if(chatJsonData.size() > pageSize)
				initSize = chatJsonData.size() - pageSize;
			
			JSONArray tmp_result = new JSONArray();
			for(int i = initSize ; i < chatJsonData.size() ; i++){
				JSONObject tmp_hash_result = new JSONObject();
				tmp_hash_result.put("seqno", Integer.toString(chatJsonData.get(i).getSeqno()));
				tmp_hash_result.put("mem_seq", chatJsonData.get(i).getMemId());
				tmp_hash_result.put("name", chatJsonData.get(i).getName());
				tmp_hash_result.put("content", chatJsonData.get(i).getContent());
				tmp_hash_result.put("reg_date", chatJsonData.get(i).getReg_Date());
				tmp_result.put(tmp_hash_result);
			}
			
			Log.d(TAG, "Saved Data to Preference: " + tmp_result.toString());
			
			JSONSharedPreferences.remove(context, "glineChat", ROOM_NUMBER);
			JSONSharedPreferences.saveJSONArray(context, "glineChat", ROOM_NUMBER, tmp_result);
    	} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private class getNewChat extends AsyncTask<Void, Void, Void>{
		private Context context;
		
		private getNewChat(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			dialog.setVisibility(View.VISIBLE);
			chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				String param_seqno = Integer.toString(prefs.getInt("chatMaxSeqno"+ROOM_NUMBER, -1));				
				Map<String, String> map = new HashMap<String, String>();
				map.put("curPageNo", param_seqno);
				map.put("ROOM_NO", ROOM_NUMBER);

				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "chat/chat_list.php", map));
				JSONObject json_header = json.getJSONObject("header");
				JSONArray json_result;
				
				
				if(json_header.getInt("count") == 0){
					JSONSharedPreferences.remove(context, "glineChat", ROOM_NUMBER);
					chatJsonData.clear();
					chatListAdapter.notifyDataSetChanged();
					isFinishedLoading = true;
					Log.e(TAG, "DATA COUNT: 0. Load Finished");
					return null;
				}

				if(json.isNull("data_result")){
					return null;
				}
				
				json_result =	json.getJSONArray("data_result");
				
				//chatJsonData.clear();
				for (int i = 0; i < json_result.length(); i++) {
					JSONObject jsonObject = json_result.getJSONObject(i);
					
					ChatData tmp_nd = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
							,jsonObject.getString("name"), jsonObject.getString("content")
							,jsonObject.getString("reg_date")
					);
					chatJsonData.addLast(tmp_nd);
					Log.d(TAG, "New Data: " + jsonObject.getInt("seqno"));
				}
				
				Log.d(TAG, "[ChatMainActivity] THIS WILL BE SAVED:::::::: " + chatJsonData.size());
				
				saveNewJSONData(context);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused)
        {
			dialog.setVisibility(View.INVISIBLE);
			
			int seq = 0;
			
			if(chatJsonData.size() > 0)
				seq = chatJsonData.get(chatJsonData.size()-1).getSeqno();
			
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            Editor edit = prefs.edit();
            //edit.putInt("chatSeqno"+ROOM_NUMBER, seq);
            edit.putInt("chatMaxSeqno"+ROOM_NUMBER, seq);
            edit.commit();
            
            if(chatJsonData != null && chatJsonData.size() > 0){
            	chatListAdapter.notifyDataSetChanged();
            }
            chatListView.setSelection(seq);
        }
	}
	
	
	private class getPrevChat extends AsyncTask<Void, Void, Void>{
		private Context context;
		private int jsonLen = 0;
		
		private getPrevChat(Context context){
			this.context = context;
		}

		@Override
		protected void onPreExecute(){
			loadingBarLayout.setVisibility(View.VISIBLE);
			chatListView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_DISABLED);
		}

		@Override
		protected Void doInBackground(Void... unused){
			
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				pageNo = (chatJsonData != null ? chatJsonData.size(): pageNo );
				
				Map<String, String> map = new HashMap<String, String>();
				map.put("pageNo", Integer.toString(pageNo));
				map.put("pageSize", Integer.toString(pageSize));
				map.put("ROOM_NO", ROOM_NUMBER);
								
				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "chat/chat_list.php", map));
				JSONObject json_header = json.getJSONObject("header");
				JSONArray json_result;
				
				pageNo += pageSize;

				if(json.isNull("data_result")){
					if(json_header.getInt("count") == 0){
						JSONSharedPreferences.remove(context, "glineChat", ROOM_NUMBER);
						chatJsonData.clear();
						chatListAdapter.notifyDataSetChanged();
						Log.e(TAG, "COUNT 0");
					}
					isFinishedLoading = true;
					Log.e(TAG, "Load Finished =========================");
				}else{
					json_result = json.getJSONArray("data_result");
					
					jsonLen = json_result.length()-1;
					
					for (int i = jsonLen; i >= 0; i--) {
						JSONObject jsonObject = json_result.getJSONObject(i);
						
						/*
						if(chatJsonData.size() > 0 && jsonObject.getInt("seqno") == chatJsonData.get(chatJsonData.size()-1).getSeqno()){
							break;
						}
						*/
						
						ChatData tmp_nd = new ChatData(jsonObject.getInt("seqno"), jsonObject.getInt("mem_seq")
								,jsonObject.getString("name"), jsonObject.getString("content")
								,jsonObject.getString("reg_date")
						);
						chatJsonData.addFirst(tmp_nd);
						
						Log.d(TAG, "Prev Data: " + jsonObject.getInt("seqno"));
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused){
        	
        	loadingBarLayout.setVisibility(View.INVISIBLE);
        	
        	if(chatJsonData != null && chatJsonData.size() > 0){
            	chatListAdapter.notifyDataSetChanged();
            }
        	
        	chatListView.setSelection(jsonLen-4);
        	
        	/*
        	
        	if(firstPrevItemLoading){
        		firstPrevItemLoading = false;
        		chatListView.setSelection(chatJsonData.size()-1);
        	}else{
	        	if(isFinishedLoading){
	        		chatListView.setSelection(0);
	        	}else
	        		
        	}
        	*/
        }
	}
	
	
	
	private class chatAdapter extends ArrayAdapter<ChatData> {
		Context context;
        private LinkedList<ChatData> items;

        public chatAdapter(Context context, int textViewResourceId, LinkedList<ChatData> items) {
            super(context, textViewResourceId, items);
            this.context = context;
            this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            ProgressBar newChatProgressBar;
            ImageButton failedButton;
            final ChatData p = items.get(position);
            boolean isMine = false;
            String titleText = "";
            
            if (p.getMemId() == prefs.getInt("MEM_SEQ", -1) || p.getMemId() == -1){
            	isMine = true;
            }
            
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (v == null) {
            	v = vi.inflate(R.layout.chat_listview_layout_mine, null);
            }
            
            if (isMine){
            	titleText			= p.getReg_Date();
            	v					= vi.inflate(R.layout.chat_listview_layout_mine, null);
            	newChatProgressBar	= (ProgressBar) v.findViewById(R.id.newChatProgressBarMine);
            }else{
            	v = vi.inflate(R.layout.chat_listview_layout, null);
            	newChatProgressBar = (ProgressBar) v.findViewById(R.id.newChatProgressBar);
            	titleText = p.getName() + "    " + p.getReg_Date();
            }
            failedButton		= (ImageButton) v.findViewById(R.id.failedButton);
            
            
            if(p.getSeqno() == -1)
            	newChatProgressBar.setVisibility(View.VISIBLE);
            else if(p.getSeqno() == -9){	// 결과 에러일경우
            	newChatProgressBar.setVisibility(View.GONE);
            	failedButton.setVisibility(View.VISIBLE);
            	
            	failedButton.setOnClickListener(new OnClickListener(){
            		
					@Override
					public void onClick(View v) {
						Log.d(TAG, "에러 전송 안되 안해..");
						Toast.makeText(context, "미개발..ㅋㅋ", Toast.LENGTH_SHORT).show();
					}
            	});
            	
            }else{
            	newChatProgressBar.setVisibility(View.INVISIBLE);
            }
            
            if (p != null) {
                    TextView m1 = (TextView) v.findViewById(R.id.noticeTitle);
                    TextView m2 = (TextView) v.findViewById(R.id.noticeContent);
                    TextView m3 = (TextView) v.findViewById(R.id.chatMemName);
                    ImageButton m4 = (ImageButton) v.findViewById(R.id.chatMemImg);
                    
                    
                    
                    //TextView m3 = (TextView) v.findViewById(R.id.membBirth);
                    if(m1 != null){
                    	m1.setText(p.getReg_Date());
                    }
                    
                    if(m2 != null){
                    	m2.setText(p.getContent());
                    	m2.setOnLongClickListener(new textLongClickListener(context, p.getContent()));
                    }
                    if(m3 != null){
                    	m3.setText(p.getName());
                    }
                    
                    if(m4 != null){
                    	AssetManager assetManager = getAssets();
                    	InputStream ims = null;
                    	try {  
                            // get input stream  
                            ims = assetManager.open("images/profiles/"+p.getMemId()+".png");
                        }
                        catch(IOException ex) {
                        	try {
								ims = assetManager.open("images/profiles/no_img.png");
							} catch (IOException e) {
								// TODO Auto-generated catch block
								Log.d(TAG, e.toString());
							}
                        }
                        
                        //Log.d(TAG, "READ IMAGE:::::::: images/profiles/"+p.getMemId());
                        Drawable d = Drawable.createFromStream(ims, null);  
                        m4.setImageDrawable(d);
                        
                    	//Resources res = getResources(); 
            			//Drawable profileImg = res.getDrawable(R.drawable.icon_sja);
                    }
                    
                    
                    //if(m3 != null)
                    //m3.setText(p.getMemberBirth());
            }
            return v;
        }
	}
	
	private class textLongClickListener implements View.OnLongClickListener{
		String content;
		Context context;
		textLongClickListener(Context context, String content){
			this.content = content;
			this.context = context;
		}
		
		@Override
		public boolean onLongClick(View v) {
			//final String [] items=new String []{"Copy","Copy"};
			final String [] items=new String []{"Copy"};
			ArrayAdapter<String> arr= new ArrayAdapter<String>(context, android.R.layout.select_dialog_item,items);
			
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setTitle("Share text to...");
			builder.setItems(items, new DialogInterface.OnClickListener(){
			
				@Override
				public void onClick(DialogInterface dialog, int which) {
					ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
					cm.setText(content);
				}
			});
			
			builder.show();
			Vibrator vibrator;
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);
			
			return false;
		}
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.chat_main_menu, menu);// xml menu
		
		MenuItem item = menu.findItem(R.id.soundCheck);
		
		JSONArray json_result;
		try {
			json_result = JSONSharedPreferences.loadJSONArray(this, "gline", "chatRoomList");
			for (int i = 0; i < json_result.length(); i++) {
				JSONObject jsonObject = json_result.getJSONObject(i);
				if(jsonObject.getInt("room_no") == Integer.parseInt(ROOM_NUMBER)){
					if(jsonObject.getInt("alarm") == 0){
						item.setTitle("알람 끄기");
						item.setIcon(R.drawable.icon_alarm_mute_medium);
					}else{
						item.setTitle("알람 켜기");
						item.setIcon(R.drawable.icon_alarm_sound_medium);
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
	}
	
	
	
	public boolean onOptionsItemSelected(MenuItem item){
		int alarmCode = 9;
		switch(item.getItemId()){
			case R.id.soundCheck:
				if(item.getTitle().equals("알람 켜기")){
					item.setTitle("알람 끄기");
					item.setIcon(R.drawable.icon_alarm_mute_medium);
					alarmImg.setVisibility(View.VISIBLE);
					muteImg.setVisibility(View.GONE);
					alarmCode = 0;
				}else{
					item.setTitle("알람 켜기");
					item.setIcon(R.drawable.icon_alarm_sound_medium);
					alarmImg.setVisibility(View.GONE);
					muteImg.setVisibility(View.VISIBLE);
				}
				new alarmStatusChange(ChatMainActivity.this, alarmCode).execute();
				break;
			case R.id.setBackground:
				
				final String [] items=new String []{"Choose a Color", "Choose from Your Gallery", "Take a New Photo", "Download from the Server"};
				ArrayAdapter<String> arr= new ArrayAdapter<String>(this, android.R.layout.select_dialog_item,items);
				
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("Choose One of the Following Options");
				builder.setItems(items, new DialogInterface.OnClickListener(){
				
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent;
						switch(which){
							case 0:
								new ChatColorPicker(ChatMainActivity.this, ChatMainActivity.this, 0xFFFFFFFF).show();
								break;
							case 1:
								/*
								Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
						        startActivityForResult(i, ACTIVITY_SELECT_IMAGE); 
						        */
								
								final int ACTIVITY_SELECT_IMAGE = 1234;
								intent = new Intent(
										//Intent.ACTION_GET_CONTENT,	// 또는 ACTION_PICK
										Intent.ACTION_PICK,
										android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);

										intent.setType("image/*");	// 모든 이미지
										intent.putExtra("crop", "true");	// Crop기능 활성화
										intent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());	// 임시파일 생성
										intent.putExtra("outputFormat",// 포맷방식
										Bitmap.CompressFormat.JPEG.toString());
										
										startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
								break;
						}
					}
				});
				
				builder.show();
				Vibrator vibrator;
				vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(50);
				
				
				break;
		}
		return false;
	}
	

	@Override
    public void colorChanged(int color) {
		
		//Log.d(TAG, ""+ Color.(Integer.toHexString(color)));
		
		//String strHex = String.format("0x%x", color).;
		
		//String strColor = color
		
		//String tbColor = color.getText().toString();
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.chatMainLayout);
		layout.setBackgroundColor(color);
		//layout.setBackgroundColor(Integer.toHexString(color));
		
    }
	
	
	
	private static final String TEMP_PHOTO_FILE = "temp.jpg";
	
	private Uri getTempUri() {
        return Uri.fromFile(getTempFile());
    }
	
	/** 외장메모리에 임시 이미지 파일을 생성하여 그 파일의 경로를 반환  */
    private File getTempFile() {
        if (isSDCARDMOUNTED()) {
            File f = new File(Environment.getExternalStorageDirectory(), // 외장메모리 경로
                    TEMP_PHOTO_FILE);
            try {
                f.createNewFile();      // 외장메모리에 temp.jpg 파일 생성
            } catch (IOException e) {
            }
 
            return f;
        } else
            return null;
    }
    
    /** SD카드가 마운트 되어 있는지 확인 */
    private boolean isSDCARDMOUNTED() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED))
            return true;
 
        return false;
    }
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
	    super.onActivityResult(requestCode, resultCode, data); 

	    switch(requestCode) { 
	    case 1234:
	    	if (resultCode == RESULT_OK) {
                if (data != null) {
                    String filePath = Environment.getExternalStorageDirectory()
                            + "/temp.jpg";
 
                    //Log.e(TAG, "FILE GET::::::::::::" + filePath); // logCat으로 경로확인.
 
                    Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
                    //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.chat_bg);
        			BitmapDrawable bitmapDrawable = new BitmapDrawable(selectedImage);
        			bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
        			
        			LinearLayout layout = (LinearLayout) findViewById(R.id.chatMainLayout);
        			layout.setBackgroundDrawable(bitmapDrawable);
                    
                    
                    // temp.jpg파일을 Bitmap으로 디코딩한다.
 
                    //ImageView _image = (ImageView) findViewById(R.id.imageView);
                    //_image.setImageBitmap(selectedImage); 
                    // temp.jpg파일을 이미지뷰에 씌운다.
                }
	    	}
	    	/*
	        if(resultCode == RESULT_OK){  
	            Uri selectedImage = data.getData();
	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	            cursor.moveToFirst();

	            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            String filePath = cursor.getString(columnIndex);
	            cursor.close();
	            
	            Log.d(TAG, "READ IMAGE:::::::: "+ filePath);

	            Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
	        }
	        */
	    }

	};
	
	private class alarmStatusChange extends AsyncTask<Void, Void, Void>{
		private Context context;
		private int alarmCode;
		private boolean responseOK;
		
		private alarmStatusChange(Context context, int alarmCode){
			this.context = context;
			this.alarmCode = alarmCode;
		}

		@Override
		protected void onPreExecute(){
			dialog.setVisibility(View.VISIBLE);
		}

		@Override
		protected Void doInBackground(Void... unused){
			try {
				httpConnectionManager hcm = new httpConnectionManager(context);
				
				Map<String, String> map = new HashMap<String, String>();
				map.put("FRM_ROOM_NO", ROOM_NUMBER);
				map.put("FRM_MEM_SEQ", prefs.getInt("MEM_SEQ", -1) + "");
				map.put("FRM_ALARM", alarmCode + "");

								
				JSONObject json = new JSONObject(hcm.readJSON_GET(getString(R.string.SERVER_URL) + "chat/chat_alarm_change.php", map));
				
				if(json == null || json.isNull("header")){
					responseOK = false;
					return null;
				}
				
				JSONObject json_header = json.getJSONObject("header");
				
				if(json_header.getInt("res_code") == 200){
					responseOK = true;
					
					JSONArray json_result;
					try {
						json_result = JSONSharedPreferences.loadJSONArray(context, "gline", "chatRoomList");
						for (int i = 0; i < json_result.length(); i++) {
							JSONObject jsonObject = json_result.getJSONObject(i);
							if(jsonObject.getInt("room_no") == Integer.parseInt(ROOM_NUMBER)){
								jsonObject.remove("alarm");
								jsonObject.put("alarm", alarmCode);
							}
						}
						
						JSONSharedPreferences.saveJSONArray(context, "gline", "chatRoomList", json_result);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					Log.i(TAG, "Alarm Status Changed::::::::::::::::::::::");
					
				}else{
					responseOK = false;
				}
				
				return null;
			} catch (Exception e) {
				e.printStackTrace();
			}
			
    		return null;
        }

        @Override
		protected void onPostExecute(Void unused){
        	dialog.setVisibility(View.INVISIBLE);
        	
        	if(!responseOK){
        		Log.i(TAG, "onPostExecute Alarm Status NOT Changed:::::::::::::::::::::: ");
        	}
        }
	}

}

